<?php
	require('database.php');
	//将post参数转换成对象
	$postData = file_get_contents('php://input', true);
	$obj=json_decode($postData);
	
	$sel="SELECT * FROM nav";
	$res=mysqli_query($conn,$sel);
	if(mysqli_num_rows($res)>0){
		while($arr=mysqli_fetch_assoc($res)){
			$nav_data[]=$arr;
		}
	}
	$data=array();
	$data['nav']=$nav_data;
	//cp
	$sid = isset($obj->ssid)?$obj->ssid:1;
	//cp总数据
	if(isset($obj->like)){//如果存在搜索就按照搜索输出cp数据
		$like=$obj->like;
		$cp_sels="SELECT * FROM product where p_name LIKE '%$like%'";
	}else{
		$cp_sels="SELECT * FROM product where s_id=$sid";
	}
	$cp_ress=mysqli_query($conn,$cp_sels);
	$total=mysqli_num_rows($cp_ress);
	if($total>0){
		while($like_name_arr=mysqli_fetch_assoc($cp_ress)){
			$like_name_data[]=$like_name_arr['p_name'];
		}
	}
	$data['like_name_data']=$like_name_data;
	$data['total']=$total;
	//每页两条数据，计算页数
	$num=2;
	$page=ceil($total/$num);
	//页数写入数组
	$p=[];
	for($i=1;$i<=$page;$i++){
		$p[count($p)]=$i;
	}
	$data['p']=$p;
	$p_num = isset($obj->p)?$obj->p:1;
	// if($p_num<$page){
	// 	$next=$p_num+1;
	// }
	$next=$p_num<=$page?$p_num+1:$page;
	$next=$next==$page+1?1:$next;
	// if($p_num>1){
	// 	$prve=$p_num-1;
	// }
	$prev=$p_num>=1?$p_num-1:1;
	$prev=$prev==0?$page:$prev;
	$data['next']=$next;
	$data['prev']=$prev;
	if($p_num>1){
		$index=$num*($p_num-1);
	}else{
		$index=0;
	}
	if(isset($obj->like)){//如果存在搜索就按照搜索输出cp数据
		$like=$obj->like;
		$cp_sel="SELECT * FROM product where p_name LIKE '%$like%' LIMIT $index,$num";
	}else{
		$cp_sel="SELECT * FROM product where s_id=$sid LIMIT $index,$num";
	}
	$cp_res=mysqli_query($conn,$cp_sel);
	if(mysqli_num_rows($cp_res)>0){
		while($cp_arr=mysqli_fetch_assoc($cp_res)){
			$cp_data[]=$cp_arr;
		}
	}
	$data['cp']=$cp_data;
	//cp_detail
	$detail_id = isset($obj->did)?$obj->did:1;
	$detail_sel="SELECT * FROM product LEFT JOIN sm_img ON product.sm_id=sm_img.sm_id where product.p_id=$detail_id";
	$detail_res=mysqli_query($conn,$detail_sel);
	if(mysqli_num_rows($detail_res)>0){
		$detail_data=mysqli_fetch_assoc($detail_res);
	}
	$data['cp_detail']=$detail_data;
	$data['did']=$detail_id;
	
	//sort
	$sort_sel="SELECT * FROM sort";
	$sort_res=mysqli_query($conn,$sort_sel);
	if(mysqli_num_rows($sort_res)>0){
		while($sort_arr=mysqli_fetch_assoc($sort_res)){
			$sort_data[]=$sort_arr;
		}
	}
	$data['sort']=$sort_data;
	//about
	$about_sel="SELECT * FROM `about`";
	$about_res=mysqli_query($conn,$about_sel);
	if(mysqli_num_rows($about_res)>0){
		$about_data=mysqli_fetch_assoc($about_res);
	}
	$data['about']=$about_data;
	//news
	$news_sel="SELECT * FROM `product` WHERE t=1";
	$news_res=mysqli_query($conn,$news_sel);
	if(mysqli_num_rows($news_res)>0){
		while($news_arr=mysqli_fetch_assoc($news_res)){
			$news_data[]=$news_arr;
		}
	}else{
		$news_data='暂无活动';
	}
	$data['news']=$news_data;
	echo json_encode($data);
?>